<template>
    <el-select size="small" v-if="type === 'id'" v-model="employees_id" :loading="loading" clearable filterable remote :remote-method="remoteMethod" placeholder="输入姓名搜索" style="height:32px" @change="onChange">
        <el-option
            v-for="item in employeesList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
        </el-option>
    </el-select>
    <el-select size="small" v-else-if="type === 'code'" v-model="code" :loading="loading" clearable filterable remote :remote-method="remoteMethod" placeholder="输入姓名搜索" style="height:32px" @change="onChange">
        <el-option
            v-for="item in employeesList"
            :key="item.id"
            :label="item.name"
            :value="item.code">
        </el-option>
    </el-select>
</template>

<script>
import {Apiemployees} from '@/api'
export default {
    name: 'employeesInput',
    props:{
        type:{
            default: 'id'
        },
        middleList:{
            default:()=>([])
        },
    },
    data(){
        return{
            employeesList: [],
            employees_id: null,
            code: null,
            loading: false,
        }
    },
    watch:{
        middleList:{
            handler(value){
                this.employeesList = value
                this.employees_id = value.length > 0 ? value[0].id : null
                this.code = value.length > 0 ? value[0].code : null
            },
            deep: true,
            immediate: true
        }
    },
    methods:{
        remoteMethod(name){
            name = name.trim()
            if(!name) {
                this.employeesList = [...this.middleList]
                return
            }
            this.loading = true
            let options = {name,allPage:2}
            Apiemployees(options).then(({data}) => {
                this.employeesList = data
            }).finally(()=>{
                this.loading = false
            })
        },
        onChange(value){
            let obj 
            if(value){
                for (const ele of this.employeesList) {
                    if(ele[this.type] === value){
                        obj = ele;
                        break;
                    }
                }
            }else{
                obj = {}
            }
            this.$emit('onChange',obj)
        },
    }
}
</script>

<style>

</style>